<template>
	<div>
		<!-- 面包屑 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/layout' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>任务管理</el-breadcrumb-item>
			<el-breadcrumb-item>任务列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片布局 -->
		<el-card>
			<!-- 植入搜索栏 -->
			<el-row :gutter="20">
				<el-col :span="5"><el-input clearable placeholder="搜索名称" v-model="searchName" clearableclear="getTaskList"></el-input></el-col>
				<el-col :span="5"><el-input clearable placeholder="搜索明细" v-model="searchDesc" clearableclear="getTaskList"></el-input></el-col>

				<el-col :span="2">
					<el-button type="primary" @click="getTaskList()">
						<el-icon><Search /></el-icon>
					</el-button>
				</el-col>
				<el-col :span="5"><el-button type="primary" @click="showAddBox = true">添加任务</el-button></el-col>
			</el-row>
			<!-- 放入table -->
			<el-table
				:data="taskList"
				style="width: 100%; height: 550px; margin-top:10px;"
				border
				:header-cell-style="{ height: '37px', padding: '0' }"
				:row-style="{ height: '37px' }"
				:cell-style="{ padding: '0' }"
			>
				<!-- 数据绑定 -->
				<el-table-column fixed label="任务id" width="80" prop="id"></el-table-column>
				<el-table-column fixed label="任务名称" width="100" prop="taskName"></el-table-column>
				<el-table-column label="任务明细" width="180" prop="taskDesc"></el-table-column>
				<el-table-column label="任务报酬" width="120" prop="salary"></el-table-column>
				<el-table-column label="任务级别" width="120" prop="level"></el-table-column>
				<el-table-column label="是否完成" width="100" prop="finished" :formatter="formatFinish"></el-table-column>
				<el-table-column label="截止时间" width="240" prop="deadline"></el-table-column>
				<el-table-column label="过期时间" width="240" prop="expired"></el-table-column>
				<el-table-column label="接收人" width="120" prop="receiver"></el-table-column>
				<el-table-column label="发布人" width="120" prop="publisher"></el-table-column>
				<el-table-column label="可用性" width="100" prop="enable">
					<template #default="scope">
						<el-select @change="changeEnableOrLock(scope.row, true)" class="el-col-sm-22" size="small" v-model="scope.row.enable">
							<el-option v-for="item in enableOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</template>
				</el-table-column>
				<el-table-column label="是否锁定" width="100" prop="lockable">
					<template #default="scope">
						<el-select @change="changeEnableOrLock(scope.row, false)" class="el-col-sm-22" size="small" v-model="scope.row.lockable">
							<el-option v-for="item in lockableOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</template>
				</el-table-column>

				<el-table-column label="创建者" width="80" prop="createBy"></el-table-column>
				<el-table-column label="创建时间" width="200" prop="createDate"></el-table-column>
				<el-table-column label="最近修改人" width="100" prop="updateBy"></el-table-column>
				<el-table-column label="最近修改" width="200" prop="lastUpdate"></el-table-column>

				<el-table-column fixed="right" label="操作" width="250">
					<template #default="scope">
						<el-button size="small" type="warning" @click="makeExpired(scope.row)">任务失效</el-button>
						<el-button size="small" @click="showEdit(scope.row)">编辑</el-button>
						<el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页模块 -->
			<el-pagination
				v-model:current-page="pageNo"
				v-model:page-size="pageSize"
				:page-sizes="[10, 20, 50, 100]"
				:small="false"
				:disabled="false"
				:background="true"
				layout="total, sizes, prev, pager, next"
				:total="totalCount"
				@size-change="onSizeChange"
				@current-change="onPageChange"
			/>
			<!-- 添加会话框 -->
			<el-dialog title="新增任务" v-model="showAddBox" width="40%" :before-close="clearEdit" style="padding: 8px 15px;" @close="onClose">
				<el-form :model="taskForm" :rules="taskFormRules" ref="taskFormRules" label-width="120px">
					<el-form-item label="任务名称" prop="taskName"><el-input v-model="taskForm.taskName"></el-input></el-form-item>
					<el-form-item label="任务明细" prop="taskDesc"><el-input :rows="3" type="textarea" v-model="taskForm.taskDesc"></el-input></el-form-item>
					<el-form-item label="任务报酬" prop="salary"><el-input v-model="taskForm.salary"></el-input></el-form-item>
					<el-form-item label="任务等级" prop="level"><el-input v-model="taskForm.level"></el-input></el-form-item>
					<el-form-item label="任务截止时间" prop="deadline">
						<el-date-picker
							v-model="taskForm.deadline"
							type="date"
							placeholder="选择截止日期"
							:disabled-date="disabledDeadDate"
							:shortcuts="shortcuts"
							format="YYYY-MM-DD"
							value-format="YYYY-MM-DD 23:59:59"
							@change="setExpried()"
						/>
					</el-form-item>

					<el-form-item label="任务过期时间" prop="expired">
						<el-date-picker
							v-model="taskForm.expired"
							type="date"
							placeholder="选择过期日期"
							:disabled-date="disabledExpiredDate"
							:shortcuts="shortcuts"
							format="YYYY-MM-DD"
						/>
					</el-form-item>

					<el-form-item class="dialog-footer">
						<el-button @click="clearEdit">取消</el-button>
						<el-button type="primary" @click="saveTaskData('taskFormRules')">确定</el-button>
					</el-form-item>
				</el-form>
			</el-dialog>

			<!-- 编辑会话框 -->
			<el-dialog title="编辑任务" v-model="showEditBox" width="40%" :before-close="clearEdit" style="padding: 8px 15px;" @close="onClose">
				<el-form :model="taskForm" :rules="taskFormRules" ref="taskFormRules" label-width="120px">
					<el-form-item label="任务名称" prop="taskName"><el-input v-model="taskForm.taskName"></el-input></el-form-item>
					<el-form-item label="任务明细" prop="taskDesc"><el-input :rows="3" type="textarea" v-model="taskForm.taskDesc"></el-input></el-form-item>
					<el-form-item label="任务报酬" prop="salary"><el-input v-model="taskForm.salary"></el-input></el-form-item>
					<el-form-item label="任务等级" prop="level"><el-input v-model="taskForm.level"></el-input></el-form-item>

					<el-form-item label="任务截止时间" prop="deadline">
						<el-date-picker
							v-model="taskForm.deadline"
							type="date"
							placeholder="选择截止日期"
							:disabled-date="disabledDeadDate"
							:shortcuts="shortcuts"
							format="YYYY-MM-DD HH:mm:ss"
							value-format="YYYY-MM-DD 23:59:59"
							@change="setExpried()"
						/>
					</el-form-item>

					<el-form-item label="任务过期时间" prop="expired">
						<el-date-picker
							v-model="taskForm.expired"
							type="date"
							placeholder="选择过期日期"
							:disabled-date="disabledExpiredDate"
							:shortcuts="shortcuts"
							format="YYYY-MM-DD HH:mm:ss"
						/>
					</el-form-item>

					<el-form-item class="dialog-footer">
						<el-button @click="clearEdit">取消</el-button>
						<el-button type="primary" @click="handleEdit(taskForm.id, 'taskFormRules')">确定</el-button>
					</el-form-item>
				</el-form>
			</el-dialog>
		</el-card>
	</div>
</template>

<script>
import { getTaskList, addTask, editTask, deleteTask, expiredTask } from '@/api/task.js';
import { ElMessage } from 'element-plus';
export default {
	data() {
		return {
			enableOptions: [
				{
					value: '0',
					label: '是'
				},
				{
					value: '1',
					label: '否'
				}
			],
			lockableOptions: [
				{
					value: '1',
					label: '是'
				},
				{
					value: '0',
					label: '否'
				}
			],
			taskLevelOptions: [
				//待定，懒得搞了
			],
			finishOption: [{ value: '1', label: '未完成' }, { value: '0', label: '已完成' }],

			showEditBox: false,
			showAddBox: false,
			searchStr: '',
			pageNo: 1,
			pageSize: 10,
			totalCount: 0,
			searchName: '',
			searchDesc: '',

			taskForm: [],
			tableData: [],
			taskList: [],

			trigger: 'blur',
			checkFlag: 0,

			taskFormRules: {
				taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
				taskDesc: [{ required: true, message: '请输入任务明细', trigger: 'blur' }],
				salary: [
					{ required: true, message: '仅能输入整数', pattern: /^[0-9]+$/, trigger: 'blur' },
					{ required: true, message: '请输入任务报酬', trigger: 'blur' },
					{ required: true, max: 10, trigger: 'blur', message: '最长仅能为十位' }
				],
				level: [
					{ required: true, message: '仅能输入数字', pattern: /^[0-9]+$/, trigger: 'blur' },
					{ required: true, message: '请输入任务级别', trigger: 'blur' },
					{ required: true, max: 1, trigger: 'blur', message: '任务等级不超过10级' }
				],
				deadline: [{ required: true, message: '请输入任务截止时间', trigger: 'blur' }],
				expired: [{ required: true, message: '请输入任务过期时间', trigger: 'blur' }]
			},
			shortcuts: [
				{
					text: '今天',
					value: new Date()
				},
				{
					text: '7天后',
					value: () => {
						const date = new Date();
						date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
						return date;
					}
				},
				{
					text: '30天后',
					value: () => {
						const date = new Date();
						date.setTime(date.getTime() + 3600 * 1000 * 24 * 30);
						return date;
					}
				}
			]
		};
	},
	methods: {
		formatFinish(row, column, cellValue, index) {
			const option = this.finishOption.find(item => item.value === cellValue);
			return option ? option.label : cellValue;
		},
		getTaskList() {
			this.searchStr = {
				name: this.searchName,
				desc: this.searchDesc
			};
			const param = { page: this.pageNo, limit: this.pageSize, searchStr: this.searchStr };
			getTaskList(param).then(resp => {
				this.totalCount = resp.total;
				this.taskList = resp.rows;
			});
		},

		saveTaskData(formname) {
			this.$refs[formname].validate(valid => {
				if (valid) {
					this.$confirm('此操作将添加该任务, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
						.then(() => {
							console.log(this.taskForm);

							const param = {
								taskName: this.taskForm.taskName,
								taskDesc: this.taskForm.taskDesc,
								salary: this.taskForm.salary,
								level: this.taskForm.level,
								deadline: this.taskForm.deadline,
								expired: this.taskForm.expired.getTime()
							};

							addTask(param).then(resp => {
								if (resp.success) {
									ElMessage.success('操作成功');
									this.showAddBox = false;
									this.taskForm = [];
									this.getTaskList();
								}
							});
						})
						.catch(ex => {
							ElMessage.error('已取消添加！' + ex);
						});
				}
			});
		},
		changeEnableOrLock(row, judge) {
			// console.log(row);
			var param = [];
			// console.log(judge);
			if (judge) {
				param = { id: row.id, enable: row.enable };
			} else {
				param = { id: row.id, lockable: row.lockable };
			}
			// console.log(param);
			addTask(param)
				.then(resp => {
					this.$message({
						type: 'success',
						message: '已修改'
					});
				})
				.catch(ex => {
					this.$message({
						type: 'error',
						message: '修改失败' + ex
					});
				});
		},

		onClose() {
			this.taskForm = [];

			//关闭弹框
			this.showAddBox = false;
			this.showEditBox = false;
		},
		clearEdit() {
			//清空表单默认值
			this.taskForm = [];
			this.checkFlag = 0;
			//关闭弹框
			this.showAddBox = false;
			this.showEditBox = false;
		},

		showEdit(row) {
			//设置id

			this.taskForm.id = row.id;
			this.taskForm.taskName = row.taskName;

			this.taskForm.taskDesc = row.taskDesc;
			this.taskForm.salary = row.salary;
			this.taskForm.level = row.level;
			this.taskForm.deadline = row.deadline;
			this.taskForm.expired = row.expired;
			//设置表单默认值

			//弹框
			this.showEditBox = true;
		},
		onSizeChange(pageSize) {
			this.pageNo = 1;
			this.pageSize = pageSize;

			this.getTaskList();
		},
		onPageChange(page) {
			this.pageNo = page;

			this.getTaskList();
		},
		disabledDeadDate(time) {
			// 禁止选择今天以前的时间
			return time.getTime() < Date.now() - 8.64e7 || time.getTime() > Date.now() + 3600 * 1000 * 24 * 30;
		},
		disabledExpiredDate(time) {
			if (this.taskForm.deadline) {
				this.checkFlag = 1;
				const deadline = new Date(this.taskForm.deadline);
				return time.getTime() < deadline.getTime() - 8.64e7 || time.getTime() > deadline.getTime() + 3600 * 1000 * 24 * 30;
			} else if (!this.taskForm.deadline && this.taskForm.expired && this.checkFlag == '0') {
				ElMessage.error('请先选择截止日期');
				this.taskForm.expired = '';
			}
		},
		setExpried() {
			var date = new Date();
			if (this.taskForm.deadline) {
				const deadline = new Date(this.taskForm.deadline);
				date.setTime(deadline.getTime() + 3600 * 1000 * 24 * 7);
				this.taskForm.expired = date;
			} else {
				this.taskForm.expired = '';
			}
		},
		//  ---确认函数
		handleEdit(editId, formName) {
			this.$refs[formName].validate(valid => {
				if (valid) {
					this.$confirm('此操作将修改该任务, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})

						.then(() => {
							const param = {
								id: editId,
								taskName: this.taskForm.taskName,
								taskDesc: this.taskForm.taskDesc,
								salary: this.taskForm.salary,
								level: this.taskForm.level,
								deadline: this.taskForm.deadline,
								expired: this.taskForm.expired.getTime()
							};
							editTask(param).then(resp => {
								if (resp.success) {
									this.$message({
										type: 'success',
										message: '修改成功!'
									});
									this.clearEdit();
									this.getTaskList();
								} else {
									this.$message({
										type: 'error',
										message: '修改失败！' + resp.message
									});
								}
							});
						})
						.catch(ex => {
							this.$message({
								type: 'error',
								message: '修改失败！' + ex
							});
						});
				} else {
					console.log('验证失败');
					return false;
				}
			});
		},
		handleDelete(index, row) {
			this.$confirm('此操作将永久删除该任务, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					const delId = { id: row.id };

					deleteTask(delId).then(resp => {
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
						this.getTaskList();
					});
				})
				.catch(ex => {
					this.$message({
						type: 'error',
						message: '删除失败！' + ex
					});
				});
		},
		makeExpired(row) {
			now = Date.now();
			const expiredTime = new Date(row.expired);
			const deadlineTime = new Date(row.deadline);
			if (now > expiredTime) {
				ElMessage.error('任务已失效，不可再次失效！');
				return;
			}
			if (row.finished === '0' && row.receiver) {
				ElMessage.error('任务已完成，不可失效！');
				return;
			}
			if (row.finished !== '0' && row.receiver) {
				ElMessage.warning('任务已被接收，请先与接收人协商一致');
				return;
			}
			if (!row.receiver) {
				this.$confirm('此操作将使其失效，无法被接收，无法被完成，是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					const param = {
						id: row.id
					};
					expiredTask(param).then(resp => {
						if (resp.success) {
							this.$message({
								type: 'success',
								message: '修改成功!'
							});
							this.clearEdit();
							this.getTaskList();
						} else {
							this.$message({
								type: 'error',
								message: '修改失败！' + resp.message
							});
						}
					});
				});
			}
		}
	},
	mounted() {
		this.getTaskList();
	}
};
</script>

<style scoped>
div.el-breadcrumb {
	height: 45px;
}

.el-dialog__body {
	padding: 0px 15px;
}

.el-form-item {
	/* height: 68px; */
}
</style>
